﻿using System;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Routing;

namespace Infrastructure.Web.Mvc.Routing
{
    public class RegexRoute : Route
    {
        #region Fields

        Regex urlPattern;

        #endregion

        #region Constructors

        public RegexRoute(Regex urlPattern, IRouteHandler routeHandler)
            : this(urlPattern, null, routeHandler) { }

        public RegexRoute(Regex urlPattern, RouteValueDictionary defaults, IRouteHandler routeHandler)
            : base(null, defaults, routeHandler)
        {
            this.urlPattern = urlPattern;
        }

        #endregion

        #region Methods

        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            string requestUrl = httpContext.Request.AppRelativeCurrentExecutionFilePath.Substring(2) + httpContext.Request.PathInfo;

            Match match = this.urlPattern.Match(requestUrl);

            RouteData data = null;

            if (match.Success)
            {
                data = new RouteData(this, RouteHandler);

                if (Defaults!=null)
                    foreach (var def in Defaults)
                        data.Values[def.Key] = def.Value;

                for (var i = 1; i < match.Groups.Count; i++)
                {
                    var group = match.Groups[i];

                    if (!group.Success) continue;
                    var key = this.urlPattern.GroupNameFromNumber(i);

                    if (!String.IsNullOrEmpty(key) && !Char.IsNumber(key, 0))
                        data.Values[key] = group.Value;
                }
            }
            else return base.GetRouteData(httpContext);

            return data;
        }

        #endregion
    }
}